<template>
  <div>
    <topHeader> </topHeader>
    <div class="innercontent">
      <div style="padding-bottom:20px;">
        <el-button-group style="margin-right:20px;">
          <el-button @click="addBanner" type="primary">添加项目</el-button>
        </el-button-group>

        <!-- <el-button style="position:absolute; left:40px;" type="primary">添 加</el-button> -->
      </div>
      <!-- 数据列表 -->
      <el-table :data="listdatas" style="width: 100%;" id="customeltable">
        <el-table-column type="index" width="40"> </el-table-column>

        <el-table-column
          label="名称"
          property="name"
          style="color: blue;"
          width="200"
        >
        </el-table-column>

        <el-table-column label="描述" property="des" width="200">
        </el-table-column>

        <el-table-column label="ID" property="id" align="center" width="100">
        </el-table-column>

        <el-table-column label="修改者" width="200" align="center">
          <template slot-scope="scope">
            <el-tag>{{ getEditUser(scope.row) }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          property="createDate"
          label="修改日期"
          align="center"
          width="160"
        >
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" @click="editSpecs(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="deleteSpecs(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="itemCount"
        >
        </el-pagination>
      </div>

      <!-- 添加,修改 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        :before-close="beforeCloseDialog"
      >
        <el-form :model="selectedData" :rules="rules" ref="theForm">
          <!--   -->
          <el-form-item label="项目名称:" prop="name">
            <el-input v-model="selectedData.name" placeholder=""></el-input>
          </el-form-item>

          <!--  -->
          <el-form-item label="项目描述:" prop="des">
            <el-input v-model="selectedData.des" placeholder=""></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelEditBanner">取 消</el-button>
          <el-button type="primary" @click="insertOrUpdate">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { projList, projCreate, projUpdate, projDelete } from "../api/getData";

import topHeader from "../views/headerTop";
import * as commonConst from "../common/commonConst";
import { checkNullString } from "@/common/mUtils";
import { getNowFormatDate } from "@/common/DateUtils";
export default {
  components: {
    topHeader
  },

  //-----数据--------
  data() {
    return {
      baseUploadUrl: "",
      listdatas: [],
      dialogTitle: "添加项目",
      dialogFormVisible: false,
      selectedData: {},
      currentSelectIndex: -1, //当前selectedData 的 index
      currentPage: 1,
      totalpage: 1,
      itemCount: 0,
      pageSize: 200, //commonConst.basePagesize,
      rules: {
        name: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
          { min: 1, max: 40, message: "长度在 1 到 40 个字符", trigger: "blur" }
        ],
        des: [
          { required: false, message: "请输入描述", trigger: "blur" },
          {
            min: 1,
            max: 200,
            message: "长度在 1 到 200 个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    setTimeout(async () => {
      this.requestDatas();
    }, 20);
  },

  computed: {
    // ...mapState(['adminInfo']),
  },
  methods: {
    //-------------------------业务逻辑---------------------------
    //获取编辑人--------
    getEditUser(item) {
      //  item 如果没有editUser的值会导致读取错误 引起 排版错误
      try {
        return typeof item.editUser == "undefined" || item.editUser == ""
          ? "Admin"
          : item.editUser;
      } catch (error) {
        return "AD";
      }
    },

    //清空选中数据源--------
    emptySelectData() {
      this.selectedData = { name: "", des: "" }; //;
      // console.log(index, obj);
    },
    //清空表单-----------
    delayResetFields(isDelay) {
      if (!this.$refs["theForm"]) {
        return;
      }

      if (isDelay) {
        //由于首次出现还没挂载,需要延时执行
        setTimeout(() => {
          this.$refs["theForm"].resetFields();
        }, 250);
      } else {
        this.$refs["theForm"].resetFields();
      }
    },

    //获取信息----------
    async requestDatas() {
      try {
        // let para = {
        //   page: this.currentPage,
        //   pagesize: this.pageSize
        // };
        const resp = await projList();
        if (resp.errorCode == 0) {
          //console.log("datas:", resp.data);
          this.listdatas = resp.data == null ? [] : resp.data;
          this.itemCount = resp.itemCount;
        } else {
          this.$message.error("获取失败");
        }
      } catch (err) {
        this.$message({
          type: "error",
          message: commonConst.error_connect_reload
        });
      }
    },

    //编辑--------
    editSpecs(index, obj) {
      this.currentSelectIndex = index;
      this.dialogTitle = "修改项目";
      this.selectedData = JSON.parse(JSON.stringify(obj)); //Object.assign({},obj) Object.assign会跳过值为null的对象
      this.dialogFormVisible = true;

      // console.log(index, obj);
    },

    //删除---------
    deleteSpecs(index, obj) {
      // this.$message.error("上传图片失败！");
      this.currentSelectIndex = index;
      this.$confirm("是否要删除该项目?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
          try {
            //这里的session实际上是加密后的密码
            // let session = localStorage.getItem(commonConst.userSessionKey);
            // session = checkNullString(session);
            // obj.adminPassword = session;

            const resp = await projDelete(obj);

            if (resp.errorCode == 0) {
              //删除元素
              this.listdatas.splice(index, 1);
              this.itemCount = this.itemCount - 1;
              //告诉菜单栏修改
              this.XCEventHandler.$emit(
                commonConst.proj_change_event,
                this.listdatas
              );
            } else {
              this.$message({
                type: "error",
                message: "删除失败"
              });
            }
          } catch (err) {
            this.$message({
              type: "error",
              message: "连接超时"
            });
          }
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
    }, //

    //更新---------
    insertOrUpdate() {
      this.$refs["theForm"].validate(async valid => {
        if (valid) {
          //修改编辑时间
          this.selectedData.createDate = getNowFormatDate();

          // //当前项目ID
          // this.selectedData.password = this.$refs.pwd.value;
          // this.selectedData.adminPassword = this.$refs.adminPwd.value;

          //插入
          if (this.selectedData.id == null) {
            try {
              const res = await projCreate(this.selectedData);

              if (res.errorCode == 0) {
                let obj = res.data;

                console.log("this.listdatas", this.listdatas);
                console.log("成功返回", res);

                this.listdatas.push(obj); //加在最后
                //this.listdatas.unshift(obj); //加在第一个
                this.$message.success("添加成功");
                this.dialogFormVisible = false;
                this.itemCount = this.itemCount + 1;

                //告诉菜单栏修改
                this.XCEventHandler.$emit(
                  commonConst.proj_change_event,
                  this.listdatas
                );
              } else {
                this.$message.error("添加失败");
              }
            } catch (err) {
              this.$message({
                type: "error",
                message: err
              });
              console.log("获取失败", err);
            }
          } else {
            //更新
            try {
              // console.log("上传的数据:", this.selectedData);

              const res = await projUpdate(this.selectedData);

              if (res.errorCode == 0) {
                this.listdatas.splice(
                  this.currentSelectIndex,
                  1,
                  this.selectedData
                ); //这样才会触发 对象里面的get/set
                //this.listdatas[this.currentSelectIndex] = Object.assign({},this.selectedData) //这样不会触发get/set
                //this.requestDatas();
                // console.log("currentSelectIndex:", this.currentSelectIndex);
                // this.requestDatas()

                this.dialogFormVisible = false;
                //告诉菜单栏修改
                this.XCEventHandler.$emit(
                  commonConst.proj_change_event,
                  this.listdatas
                );
              } else {
                this.$message.error("添加失败");
              }
            } catch (err) {
              this.$message({
                type: "error",
                message: err
              });
              console.log("获取失败", err);
            }
          }
        } else {
          console.log("输入校验失败");
        }
      });
    },

    //上移下移--------
    async moveIsUp(index, obj, isUp) {
      var targetIndex = 0;

      //上移
      if (isUp) {
        if (index == 0) {
          alert("已经置顶");
          return;
        }

        targetIndex = index - 1;
      } else {
        //下移
        if (index == this.listdatas.length - 1) {
          alert("已经到底");
          return;
        }

        targetIndex = index + 1;
      }

      var targetObj = this.listdatas[targetIndex];

      try {
        var data = {
          id1: obj.id,
          sort1: obj.sort,
          id2: targetObj.id,
          sort2: targetObj.sort,
          col: "homeBanner"
        };
        const resp = await generalSort(data);
        if (resp.errorCode == 0) {
          this.$message.success("设置排序成功");
          obj.sort = data.sort2;
          targetObj.sort = data.sort1;
          this.$set(this.listdatas, targetIndex, obj);
          this.$set(this.listdatas, index, targetObj);
        } else {
          this.$message.error("获取失败");
        }
      } catch (err) {
        this.$message.error(commonConst.error_connect_reload);
      }
    },

    //取消编辑---------
    cancelEditBanner() {
      this.dialogFormVisible = false;
    },

    //点击添加按钮--------
    addBanner() {
      this.delayResetFields(false);

      this.dialogTitle = "添加项目";
      this.emptySelectData();
      this.dialogFormVisible = true;
    },

    //导出到Android--------
    exportAndroid() {
      window.location.href = commonConst.baseUrl + "/api/exportLang/android";
    },

    //导出到iOS--------
    exportIOS() {
      // window.open("http://localhost:8083/api/exportLang/iOS");
      window.location.href = commonConst.baseUrl + "/api/exportLang/iOS";
    },

    //==========其他组件方法=======
    //dialog组件回调--------
    beforeCloseDialog(done) {
      //真正关闭
      done();

      this.emptySelectData();
      this.delayResetFields(false);
    },

    //上传组件 成功--------
    handleServiceImgScucess(res, file) {
      //console.log("resp:", res);

      if (res.errorCode == 0) {
        this.selectedData.img = res.data[0].url;
        console.log("图片:", this.selectedData.img);
        //this.$message.success("上传图片成功！");
      } else {
        this.$message.error("上传图片失败！");
      }
    },
    //上传组件 失败 , 一般是服务器挂掉或网络不行--------
    handleServiceImgError(res, file) {
      this.$message.error("上传失败,请稍后再试");
    },

    //上传组件 上传前--------
    beforeImgUpload(file) {
      const isRightType =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isRightType) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isRightType && isLt2M;
    },
    //分页组件 回调--------
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    //分页组件 处理当前分页请求 回调--------
    handleCurrentChange(val) {
      this.currentPage = val;
      // console.log(this.currentPage)
      this.requestDatas();
    }
  },
  watch: {}
};
</script>

<style lang="less" scoped>
@import "../style/mixin.less";
</style>
